<template>
  <div class="app-container">
    <el-form
      label-position="top"
      v-show="state.showSearch"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
    >
      <el-form-item label="所在城市" prop="cityName">
        <el-select @change="handleChange" v-model="queryParams.cityName" placeholder="请选择">
          <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderSn">
        <el-input class="form-input" v-model="queryParams.orderSn" placeholder="订单编号" />
      </el-form-item>
      <el-form-item label="物流状态" prop="logisticsStatus">
        <el-select
          class="form-input"
          v-model="queryParams.logisticsStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in product_logistics_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="销售类型" prop="mallProductType">
        <el-select
          class="form-input"
          v-model="queryParams.mallProductType"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in shopping_sale_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select class="form-input" v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
            v-for="dict in order_product_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="下单时间" prop="timeRange">
        <el-date-picker
          style="width: 360px"
          v-model="queryParams.timeRange"
          type="datetimerange"
          :shortcuts="shortcuts"
          range-separator="~"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input class="form-input" v-model="queryParams.mobile" placeholder="手机号" />
      </el-form-item>
      <el-form-item label="快递单号" prop="logisticsSn">
        <el-input
          class="form-input"
          v-model="queryParams.logisticsSn"
          placeholder="请输入快递单号"
        />
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['shopping:order:export']"
          type="primary"
          :disabled="disabled"
          @click="handleExport"
          >导出</el-button
        >
        <el-button
          v-hasPermi="['shopping:order:refunds']"
          type="primary"
          :disabled="disabled"
          @click="handleRefunds"
          >批量退款</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList" @selection-change="onSelectChange">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column
        label="订单编号"
        align="center"
        prop="orderSn"
        width="150"
        fixed="left"
        sortable
      />
      <el-table-column label="支付方订单编号" width="150" align="center" prop="paySn" />
      <el-table-column label="订单状态" align="center" width="100">
        <template #default="{ row }">
          <dict-tag :options="order_product_status" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="物流状态" align="center" width="100">
        <template #default="{ row }">
          <dict-tag :options="product_logistics_status" :value="row.logisticsStatus" />
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" width="100" />
      <el-table-column
        label="用户名称"
        align="center"
        prop="nickName"
        min-width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true" />
      <el-table-column
        label="所在城市"
        :show-overflow-tooltip="true"
        align="center"
        prop="cityName"
      />
      <el-table-column label="手机号" align="center" prop="mobile" width="140" />
      <el-table-column label="支付时间" align="center" prop="payTime" width="100" />
      <el-table-column
        label="商品名称"
        align="center"
        prop="productName"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="销售价格" align="center" width="120px" prop="sellPrice" />
      <el-table-column label="销售类型" align="center" width="100">
        <template #default="{ row }">
          <dict-tag :options="shopping_sale_type" :value="row.mallProductType" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template #default="{ row }">
          <el-button
            v-hasPermi="['shopping:order:details']"
            link
            type="primary"
            @click="handleTableAction(row, 'detail')"
            >详情</el-button
          >
          <el-button
            link
            type="primary"
            v-if="handleShow(row)"
            v-hasPermi="['shopping:order:refund']"
            @click="handleTableAction(row, 'refund')"
          >
            退款
          </el-button>
          <el-button
            v-if="row.status === 7"
            link
            type="primary"
            v-hasPermi="['shopping:order:mark']"
            @click="handleTableAction(row, 'enter')"
          >
            录入快递单号
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="table-bottom">
      <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
      <div class="bottom-stat">
        已选：{{ selectedObj.count }}条， 合计金额：{{ selectedObj.total }}
      </div>
    </div>
    <el-dialog
      title="录入快递单号"
      width="500"
      v-model="state.enterVisible"
      :close-on-click-modal="false"
    >
      <div class="enter-dialog" style="margin-top: -20px">
        <div style="margin-bottom: 10px">快递单号</div>
        <div>
          <el-input
            style="width: 260px"
            v-model="logisticsInfo.logisticsSn"
            placeholder="请输入快递单号"
          />
        </div>
      </div>
      <template #footer>
        <el-button type="primary" plain @click="handleEnter(false)"> 取消 </el-button>
        <el-button type="primary" :loading="entering" @click="handleEnter(true)"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderList">
import { ElMessageBox } from 'element-plus'
import { onMountedOrActivated } from '@/hooks/common'
import useGlobalStore from '@/store/modules/global'
import { enteringLogisticsSnApi, getProductOrderListApi, refundProductApi } from '@/api/shopping'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const router = useRouter()
const queryRef = ref(null)
const { proxy } = getCurrentInstance()
const { order_product_status, product_logistics_status, shopping_sale_type } = proxy.useDict(
  'order_product_status',
  'product_logistics_status',
  'shopping_sale_type'
)
const logisticsInfo = reactive({
  logisticsSn: '',
  id: ''
})
const entering = ref(false)
const tableList = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  cityName: ''
})
const selectedObj = ref({
  count: 0,
  total: 0
})
const state = reactive({
  visible: false,
  enterVisible: false,
  showSearch: true,
  total: 0,
  loading: false
})

const shortcuts = [
  {
    text: '最近三天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
      return [start, end]
    }
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

function handleSearch(confirm) {
  !confirm && queryRef.value?.resetFields()

  queryParams.value.pageNum = 1
  getList()
}
/**批量退款 */
function handleRefunds() {
  if (!selectedObj.value.count) return proxy.$modal.msgWarning('请选择订单')

  const isAllPayStatus = batchRefundOrderList.value.find(
    (i) => i.status !== 3 && i.status !== 2 && i.status !== 7
  )
  if (isAllPayStatus)
    return proxy.$modal.msgWarning('请选择订单状态为【已完成】或【待收货】或【待发货】的订单')
  ElMessageBox.confirm(
    `批量退款操作不可逆，是否进行批量退款？`,
    '批量退款',

    {
      confirmButtonText: '批量退款',
      cancelButtonText: '取消',
      type: 'warning',
      center: false
    }
  ).then(() => {
    state.loading = true
    console.log('调用批量退款接口')
    const params = batchRefundOrderList.value.map((i) => i.id)
    refundProductApi(params)
      .then(() => {
        state.loading = false
        proxy.$modal.msgSuccess('批量退款成功')
        getList()
      })
      .catch(() => {
        state.loading = false
      })
  })
}
const batchRefundOrderList = ref([])
function onSelectChange(arr) {
  console.log(arr)
  batchRefundOrderList.value = arr
  selectedObj.value.count = arr.length
  const totalPrice =
    arr.reduce((prev, { price = price || 0 }) => prev + Math.round(price * 100), 0) / 100
  const totalIntegral =
    arr.reduce((prev, { integral }) => prev + Math.round(integral * 100), 0) / 100
  selectedObj.value.total = `金额${totalPrice}元  积分${totalIntegral}粒`
}
/**退款按钮是否展示 */
function handleShow(row) {
  return row.status === 3 || row.status === 2 || row.status === 7
}
async function getList() {
  state.loading = true
  const { timeRange = [], ...data } = queryParams.value
  if (timeRange?.length) {
    data.startTime = timeRange[0]
    data.endTime = timeRange[1]
  }
  try {
    const r = await getProductOrderListApi(data)
    tableList.value = r?.rows || []
    state.total = r?.total || 0
  } finally {
    state.loading = false
  }
}
/**table Action */
function handleTableAction(obj, operType) {
  if (operType == 'detail') {
    router.push({ path: `/shopping/productOrderDetail`, query: { id: obj?.id } })
  } else if (operType == 'refund') {
    ElMessageBox.confirm('确认要退款吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(({ value }) => {
      refundProductApi([obj.id]).then(() => {
        proxy.$modal.msgSuccess('操作成功')
        getList()
      })
    })
  } else if (operType == 'enter') {
    logisticsInfo.id = obj.id
    logisticsInfo.logisticsSn = ''
    state.enterVisible = true
  }
}

/**enterDialog form */
async function handleEnter(confrim) {
  if (!confrim) return (state.enterVisible = false)

  if (!logisticsInfo.logisticsSn) {
    proxy.$modal.msgWarning('请输入快递单号')
    return
  }
  entering.value = true
  try {
    await enteringLogisticsSnApi(logisticsInfo)
    state.enterVisible = false
    proxy.$modal.msgSuccess('操作成功')
    getList()
  } finally {
    entering.value = false
  }
}

const disabled = ref(false)
function handleExport() {
  disabled.value = true
  const { timeRange = [], ...data } = queryParams.value
  if (timeRange?.length) {
    data.startTime = timeRange[0]
    data.endTime = timeRange[1]
  }
  proxy
    .download(
      '/operation/mallOrder/mallOrderDerive',
      { ...data },
      `商品订单列表${new Date().getTime()}.xlsx`
    )
    .then(() => {
      disabled.value = false
    })
    .catch((err) => {
      disabled.value = false
    })
}

function handleChange() {
  queryParams.value.tagId = ''
  getList()
}

/*onActivated*/
onMountedOrActivated(getList)
</script>

<style lang="scss" scoped>
.table-bottom {
  position: relative;
  .bottom-stat {
    position: absolute;
    top: 15px;
    left: 0;
    font-size: 14px;
    color: var(--el-pagination-text-color);
  }
}
.refund-dialog {
  line-height: 2em;
  .el-textarea {
    margin: 20px 0;
  }
  ::v-deep .el-input__inner {
    text-align: left;
  }
}

.form-input {
  width: 210px;
}
</style>
